package utils

import (
	"encoding/json"
	"fmt"
	"log"
	"strconv"
	"strings"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

type AliyunCode struct{}

func CreteClient(accessKeyId string, accessKeySecret string, endpoint string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: &accessKeyId,
		// 必填，您的 AccessKey Secret
		AccessKeySecret: &accessKeySecret,
		// Endpoint :Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
		Endpoint: &endpoint,
	}
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

func (u AliyunCode) Send(code int, phone string) interface{} {
	cilent, _err := CreteClient("LTAI5t5Z5zCKXhhqXsf1yMe7", "H71UQEE6pFmrU0nZLsHMbc8VvrWCdK", "dysmsapi.aliyuncs.com")
	if _err != nil {
		return _err
	}
	singName := "阿里云短信测试"
	TemplateCode := "SMS_154950909"
	data := "{\"code\":\"" + strconv.Itoa(code) + "\"}"
	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  &phone,
		SignName:      &singName,
		TemplateCode:  &TemplateCode,
		TemplateParam: &data,
	}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		res, _err2 := cilent.SendSmsWithOptions(sendSmsRequest, &util.RuntimeOptions{})
		if _err2 != nil {
			return _err2
		}
		log.Println(res)
		return nil
	}()
	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// 错误message
		// fmt.Println(tea.StringValue(error.Message))
		// 诊断地址
		var data interface{}
		d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
		d.Decode(&data)
		if m, ok := data.(map[string]interface{}); ok {
			recommend, _ := m["Recommend"]
			fmt.Println(recommend)
		}
		_, _err := util.AssertAsString(error.Message)
		if _err != nil {
			return _err
		}
		return _err
	}
	return true
}
